package com.liuc.practice.server.thread;

import com.liuc.practice.server.pojo.Request;
import com.liuc.practice.server.pojo.Response;
import com.liuc.practice.server.servlet.HttpServlet;
import com.liuc.practice.server.servlet.Servlet;
import com.liuc.practice.server.util.HttpProtocolResponseUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Map;
import java.util.Set;

/**
 * @Author Liu Chang
 * @Date 2021/7/23 12:25 上午
 */
public class RequestProcessor extends Thread {

    private Socket socket;

    private Map<String, Map<String, HttpServlet>> contextMap;

    public RequestProcessor(Socket socket, Map<String, Map<String, HttpServlet>> contextMap) {
        this.socket = socket;
        this.contextMap = contextMap;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String url = request.getUrl();
            String resourceName = url.substring(url.lastIndexOf("/") + 1);
            // 根据 map 中是否有 url 区别是否为动态请求
            for(Map.Entry<String, Map<String, HttpServlet>> entry : contextMap.entrySet()) {
                String context = entry.getKey();
                Map<String, HttpServlet> wrappers = entry.getValue();
                // 确定 webApplication
                if (url.contains(context)) {
                    if (resourceName.contains(".html")) {
                        response.outputHtml(entry.getKey() + "/" + resourceName);
                    } else {
                        for (Map.Entry<String, HttpServlet> servletEntry : wrappers.entrySet()) {
                            if (resourceName.contains(servletEntry.getKey().replaceFirst("/", ""))) {
                                HttpServlet servlet = servletEntry.getValue();
                                servlet.service(request, response);
                            } else {
                                response.output(HttpProtocolResponseUtil.notFound());
                            }
                        }
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // serverSocket.close();

    }
}
